package com.lsx.controller;

import com.lsx.pojo.Detailed;
import com.lsx.pojo.Enclosure;
import com.lsx.pojo.User;
import com.lsx.service.impl.EnclosureServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * Created by pc on 2017/11/21.
 */
@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private EnclosureServiceImpl enclosureService;

    /*
     *采用spring提供的上传文件的方法
     */
    @RequestMapping("Upload")
    public String springUpload(HttpServletRequest request,int did,int isfile,HttpSession session) throws IllegalStateException, IOException
    {
        User user=(User)session.getAttribute("user");
        long  startTime=System.currentTimeMillis();
        String fileName=null;
        String filepath=null;
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String path="E:/photos/"+file.getOriginalFilename();
                    //上传
                    file.transferTo(new File(path));
                    fileName=file.getOriginalFilename();
                    filepath=path;
                }
            }
        }
        System.out.println(did+"==="+fileName+"==="+filepath);
        Enclosure enclosure=new Enclosure();
        enclosure.setDid(did);
        enclosure.setUserId(user.getId());
        enclosure.setEname(fileName);
        enclosure.setEpath(filepath);
        String ip=request.getRemoteAddr();
        System.out.println("==="+ip);
        enclosure.setIp(ip);
        SimpleDateFormat cd = new SimpleDateFormat("yyyy-MM-dd");
        String createdate=cd.format(new Date());
        SimpleDateFormat ct = new SimpleDateFormat("HH:mm:ss");
        String createtime=ct.format(new Date());
        enclosure.setCreatedate(createdate);
        enclosure.setCreatetime(createtime);
        enclosureService.addelure(enclosure);
        if (isfile==0){
            Detailed detailed=new Detailed();
            detailed.setIsfile(1);
            detailed.setId(did);
            enclosureService.upDetlEid(detailed);
        }
        return "success";
    }

    @RequestMapping(value="down")
    public void downloadLocal(HttpServletResponse response,String fileName) throws FileNotFoundException {
        response.setContentType("application/x-download");
        // 下载本地文件
        //String fileName = "新建文本文档.txt";
        // 读到流中
        InputStream inStream = new FileInputStream("E:/"+fileName);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        try {
            fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");//文件的默认保存名
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value="getByDid")
    @ResponseBody
    public List<Enclosure> getByDid(int did){
        List<Enclosure> enclosures=enclosureService.getByDid(did);
        return enclosures;
    }


}
